//
//  SEInquiryViewModel.swift
//  SmartEyeForDoctor
//
//  Created by QDSG on 2021/4/20.
//

import UIKit

class SEInquiryViewModel: SEBaseViewModel {

    private let loadHomeDataQueue = DispatchQueue(label: "loadHomeData", attributes: .concurrent)
    private let loadHomeDataGroup = DispatchGroup()

    var status: SEHttpStatus = .success

    var inquiryList: [SEInquiryDetail] = []
    var inquiryDetail = SEInquiryDetail()

    var userInfoViewModel = SEUserInfoViewModel(withLoading: false)
    
    var numberOfRows: Int { inquiryList.count }
    
    var messageCount: String? {
        let sum = inquiryList.compactMap { $0.unReadCount }.reduce(0, +)
        if sum <= 0 {
            return nil
        } else if sum > 99 {
            return "99+"
        } else {
            return "\(sum)"
        }
    }
    
    convenience init(inquiryDetail: SEInquiryDetail) {
        self.init()
        self.inquiryDetail = inquiryDetail
    }
    
    func viewModel(at indexPath: IndexPath) -> SEInquiryViewModel {
        return SEInquiryViewModel(inquiryDetail: inquiryList[indexPath.row])
    }
    
    var sexImage: UIImage? {
        return inquiryDetail.patientSex == 1
            ? Asset.iconSexMale.image
            : Asset.iconSexFemale.image
    }
    
    var patientAge: String {
        guard let age = inquiryDetail.patientAge else { return "" }
        return "\(age)岁"
    }
    
    var content: String? {
        switch inquiryDetail.msgType {
        case .image:         return "[图片]"
        case .prescription:  return "[诊断结果]"
        case .checkReport:   return "[眼科检查AI报告]"
        case .fileAuthorize: return "[调阅健康档案确认]"
        case .endInquiry:    return "[结束问诊确认]"
        case .videoCall:     return "[视频通话]"
        default:             return inquiryDetail.content
        }
    }

    var abortPrescriptionCount: Int = 0

    var doctorCountModel = DoctorCountsDtoModel()

    var loadDataHandler: ((SEHttpStatus) -> Void)?
    
    var avatarPlaceholder: UIImage? {
        inquiryDetail.patientSex == 1
            ? Asset.iconPatientAvatarMale.image
            : Asset.iconPatientAvatarFemale.image
    }
    
    // MARK: - 聊天界面 病情描述
    
    var guideInquiryTime: Int = 900
    
    var isTableHeaderExpand: Bool = false {
        didSet {
            let descMaxHeight = inquiryDetail.illness?.height(width: UIScreen.screenWidth - 15 * 2 - 14 * 2,
                                                     font: .regular(14)) ?? 0
            let descDoubleHeight = inquiryDetail.illness?.heightForSingleLine(font: .regular(14)) ?? 0 * 2
            
            var descHeight: CGFloat = 0
            
            if isTableHeaderExpand {
                collectionViewHeight = numberOfItems == 0 ? 0 : kChatInquiryInfoHeaderCollectionDefaultHeight
                descHeight = max(descMaxHeight, descDoubleHeight)
            } else {
                collectionViewHeight = 0
                descHeight = min(descMaxHeight, descDoubleHeight)
            }
            tableHeaderViewHeight = kChatInquiryInfoHeaderDefaultHeight + descHeight + collectionViewHeight - kChatInquiryInfoHeaderDescLabelDetfaultHeight
        }
    }
    
    private(set) var tableHeaderViewHeight: CGFloat = kChatInquiryInfoHeaderDefaultHeight
    
    private(set) var collectionViewHeight: CGFloat = 0
    
    var unReadHidden: Bool { inquiryDetail.unReadCount == 0 }
    var unReadCount: String { "\(inquiryDetail.unReadCount)" }
    var dateTime: String {
        if let lastReadTime = inquiryDetail.lastReadTime, !lastReadTime.isEmpty {
            return Date.stringToDate(lastReadTime).chatTimeString
        } else {
            guard let createTime = inquiryDetail.createTime, !createTime.isEmpty else { return "" }
            return Date.stringToDate(createTime).chatTimeString
        }
    }
    
    var numberOfItems: Int { inquiryDetail.picList?.count ?? 0 }

    func requestHomeData() {
        loadHomeDataGroup.enter()
        loadHomeDataQueue.async { [weak self] in
            self?.requestUserInfo()
        }

        loadHomeDataGroup.enter()
        loadHomeDataQueue.async { [weak self] in
            self?.getDoctorCountsDto()
        }

        loadHomeDataGroup.enter()
        loadHomeDataQueue.async { [weak self] in
            self?.getAbortPrescriptionCount()
        }

        loadHomeDataGroup.notify(queue: DispatchQueue.main) { [weak self] in
            guard let self = self else { return }
            self.loadDataHandler?(self.status)
        }
    }
    
    /// 获取问诊列表 (type: 1 - 当前接诊 2 - 历史接诊)
    func getListOfInquiry(type: SEInquiryType, more: Bool) {
        page = more ? page + 1 : page
        SEHttpManager.shared.request(SEInquiryAPI.inquiryList(type: type.rawValue, page: page), model: SEInquiryModel.self) { (model, httpStatus) in
            switch httpStatus {
            case .success:
                if !more {
                    self.inquiryList = model?.list ?? []
                } else {
                    self.inquiryList.append(contentsOf: model?.list ?? [])
                }
                self.hasMore = model?.totalPage ?? 0 > self.page
                
                self.encodeInquiryModels(type: type)
                
            case .auth(let message), .failure(let message):
                SEHUD.showError(message: message)
            }
            self.updateData?(httpStatus)
        }
    }
    
    /// 获取问诊详情
    func getDetailOfInquiry(id: String) {
        SEHttpManager.shared.request(SEInquiryAPI.inquiryDetail(id: id), model: SEInquiryDetail.self, withLoading: true) { (model, httpStatus) in
            switch httpStatus {
            case .success:
                self.inquiryDetail = model ?? SEInquiryDetail()
            case .auth(let message), .failure(let message):
                SEHUD.showError(message: message)
            }
            self.updateData?(httpStatus)
        }
    }

    /// 获取驳回处方数量
    func getAbortPrescriptionCount() {
        SEHttpManager.shared.request(SEInquiryAPI.abortPrescriptionCount, model: Int.self) { result, status in
            switch status {
            case .success:
                self.abortPrescriptionCount = result ?? 0
            default:
                break
            }
            self.status = status
            self.loadHomeDataGroup.leave()
        }
    }

    /// 获取医生相关聚合数据
    func getDoctorCountsDto() {
        SEHttpManager.shared.request(SEInquiryAPI.doctorCountsDto, model: DoctorCountsDtoModel.self) { model, status in
            switch status {
            case .success:
                self.doctorCountModel = model ?? DoctorCountsDtoModel()
            default:
                break
            }
            self.status = status
            self.loadHomeDataGroup.leave()
        }
    }

    /// 获取用户信息
    func requestUserInfo() {
        userInfoViewModel.requestUserInfo()
        userInfoViewModel.updateData = { status in
            self.status = status
            self.loadHomeDataGroup.leave()
        }
    }
}

// MARK: - 数据持久化

extension SEInquiryViewModel {
    func decodeInquiryModels(type: SEInquiryType) {
        guard let saveModel = UserDefaults.standard.object(forKey: type.userdefaults) as? Data else { return }
        
        let jsonDecoder = JSONDecoder()
        
        guard let models = try? jsonDecoder.decode([SEInquiryDetail].self, from: saveModel) else { return }
        
        inquiryList = models
        
        updateData?(.success)
    }
    
    private func encodeInquiryModels(type: SEInquiryType) {
        let jsonEncoder = JSONEncoder()
        
        guard let saveData = try? jsonEncoder.encode(inquiryList) else { return }
        
        UserDefaults.standard.set(saveData, forKey: type.userdefaults)
    }
}
